package cn.vconinfo.base.redis;


import cn.vconinfo.base.utils.StringUtils;

/**
 *  分布式全局锁工具类
 */
public class GlobalLockUtils implements AutoCloseable {

    private static final String redis_global_lock = "redis_{global}_lock";

    private String strRedisLock;

    private long lockTime;

    /**
     *  传入调用的类
     *
     * @param clazz
     */
    public GlobalLockUtils(Class<?> clazz){
        this.strRedisLock = redis_global_lock.replaceAll("global", clazz.getName());
    }

    /**
     *  获取全局锁
     *
     * @return
     */
    public Boolean acquireGlobalLock() {
        lockTime = System.currentTimeMillis() + 1000;
        boolean isLock = RedisLock.lock(strRedisLock, StringUtils.null2Str(lockTime), 2L, 3, 100L);
        return isLock;
    }

    @Override
    public void close() throws Exception {
        // 解锁
        RedisLock.unlock(strRedisLock, StringUtils.null2Str(lockTime));
    }
}